package cn.iocoder.yudao.module.signature.service.device;

import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.ipa.MbUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.infra.api.file.FileApi;
import cn.iocoder.yudao.module.member.api.wechat.WechatMsgApi;
import cn.iocoder.yudao.module.signature.appconnect.exception.AppStoreConnectException;
import cn.iocoder.yudao.module.signature.appconnect.model.BundleIdPlatform;
import cn.iocoder.yudao.module.signature.appconnect.model.Device;
import cn.iocoder.yudao.module.signature.appconnect.model.DeviceAttributes;
import cn.iocoder.yudao.module.signature.appconnect.model.Profile;
import cn.iocoder.yudao.module.signature.appconnect.util.AppleConnectUtil;
import cn.iocoder.yudao.module.signature.appconnect.util.TokenUtil;
import cn.iocoder.yudao.module.signature.controller.admin.device.vo.AppleDevicePageReqVO;
import cn.iocoder.yudao.module.signature.controller.admin.device.vo.AppleDeviceResp;
import cn.iocoder.yudao.module.signature.controller.admin.device.vo.AppleDeviceSaveReqVO;
import cn.iocoder.yudao.module.signature.dal.dataobject.developeraccount.DeveloperAccountDO;
import cn.iocoder.yudao.module.signature.dal.dataobject.device.AppleDeviceDO;
import cn.iocoder.yudao.module.signature.dal.mysql.device.AppleDeviceMapper;
import cn.iocoder.yudao.module.signature.enums.AppleAccountType;
import cn.iocoder.yudao.module.signature.enums.AppleDeviceType;
import cn.iocoder.yudao.module.signature.enums.ClassType;
import cn.iocoder.yudao.module.signature.enums.DeviceVersionType;
import cn.iocoder.yudao.module.signature.model.GetAvailableAccountModel;
import cn.iocoder.yudao.module.signature.model.MobileProvisionCreateModel;
import cn.iocoder.yudao.module.signature.model.MobileProvisionExtractMode;
import cn.iocoder.yudao.module.signature.model.MobileProvisionResultModel;
import cn.iocoder.yudao.module.signature.service.developeraccount.DeveloperAccountService;
import cn.iocoder.yudao.module.signature.validatap12status.dto.CertStatusDTO;
import cn.iocoder.yudao.module.signature.validatap12status.util.CertUtil;
import cn.iocoder.yudao.module.signature.validatap12status.util.OCSPUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.ws.rs.client.ResponseProcessingException;
import java.io.File;
import java.time.ZoneId;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.THIRD_TYPE_ERROR;
import static cn.iocoder.yudao.module.signature.enums.ErrorCodeConstants.APPLE_DEVICE_NOT_EXISTS;

/**
 * 苹果设备信息 Service 实现类
 *
 * @author base
 */
@Service
@Validated
@Slf4j
public class AppleDeviceServiceImpl implements AppleDeviceService {

    @Resource
    private AppleDeviceMapper appleDeviceMapper;

    @Resource
    private DeveloperAccountService developerAccountService;

    @Resource
    private FileApi fileApi;

    @Resource
    private WechatMsgApi wechatMsgApi;

    @Override
    public Long createAppleDevice(AppleDeviceSaveReqVO createReqVO) {
        // 插入
        AppleDeviceDO appleDevice = BeanUtils.toBean(createReqVO, AppleDeviceDO.class);
        appleDeviceMapper.insert(appleDevice);
        // 返回
        return appleDevice.getId();
    }

    @Override
    public void updateAppleDevice(AppleDeviceSaveReqVO updateReqVO) {
        // 校验存在
        validateAppleDeviceExists(updateReqVO.getId());
        // 更新
        AppleDeviceDO updateObj = BeanUtils.toBean(updateReqVO, AppleDeviceDO.class);
        appleDeviceMapper.updateById(updateObj);
    }

    @Override
    public void deleteAppleDevice(List<Long> ids) {
        // 校验存在
//        validateAppleDeviceExists(id);
        // 删除
        appleDeviceMapper.deleteByIds(ids);
    }

    private void validateAppleDeviceExists(Long id) {
        if (appleDeviceMapper.selectById(id) == null) {
            throw exception(APPLE_DEVICE_NOT_EXISTS);
        }
    }

    @Override
    public AppleDeviceDO getAppleDevice(Long id) {
        return appleDeviceMapper.selectById(id);
    }

    @Override
    public PageResult<AppleDeviceDO> getAppleDevicePage(AppleDevicePageReqVO pageReqVO) {
        return appleDeviceMapper.selectPage(pageReqVO);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public MobileProvisionResultModel createMobileProvision(MobileProvisionCreateModel createModel) throws Exception {
        log.info("开始生成描述文件", JSON.toJSONString(createModel));
        MobileProvisionResultModel model = new MobileProvisionResultModel();

//        1.先取启用状态的账号。2.再去对应版本名称的账号。3.如果是秒出、摆烂则优先取是否优先按钮的账号
//        1.前20条打开了是否优先按钮的账号只跑到mac余量为90 iPhone余量为90的时候则进行禁用账号
//        如果中间遇到出不了描述文件的情况则跳过 寻找能秒出描述文件的账号。
        DeveloperAccountDO accountDO = null;
        BundleIdPlatform bundleIdPlatform = BundleIdPlatform.IOS;
        GetAvailableAccountModel queryModel = new GetAvailableAccountModel();
        queryModel.setVersionType(createModel.getVersionType());
        if (createModel.getClassType().equals(ClassType.APPOINTMENT)) {
            queryModel.setAppointmentFlag(1);
        } else {
            queryModel.setAppointmentFlag(0);
        }

        //公共池
        if (createModel.getAccountType().equals(AppleAccountType.PUBLIC_POOL)) {
            queryModel.setAccountBelongType(AppleAccountType.PUBLIC_POOL.getType());

            //根据设备类型选择对应的账号
            if (createModel.getDeviceType().equals(AppleDeviceType.PAD)) {
                queryModel.setIpadRemainingLimit(0);
                queryModel.setIpadFlag(1);
            } else {
                queryModel.setIpadFlag(0);
                if (createModel.getUdid().length() == 25) {
                    bundleIdPlatform = BundleIdPlatform.MAC_OS;
                    queryModel.setMacRemainingLimit(0);
                } else {
                    queryModel.setIphoneRemainingLimit(0);
                }
            }

            //秒出摆烂
            if (createModel.getClassType().equals(ClassType.SECOND) || createModel.getVersionType().equals(DeviceVersionType.SLACKING.getCode())) {
                if (createModel.getDeviceType().equals(AppleDeviceType.IPHONE)) {
                    queryModel.setPreferFlag(1);
                    if (queryModel.getMacRemainingLimit() != null) {
                        queryModel.setMacRemainingLimit(90);
                    }
                    if (queryModel.getIphoneRemainingLimit() != null) {
                        queryModel.setIphoneRemainingLimit(90);
                    }

                }

            }

            accountDO = developerAccountService.getAvailableDeveloperAccount(queryModel);

            if (createModel.getDeviceType().equals(AppleDeviceType.IPHONE)) {
                //如果没有找到账号  去掉优先标识
                if (accountDO == null) {
                    queryModel.setPreferFlag(0);
                    accountDO = developerAccountService.getAvailableDeveloperAccount(queryModel);
                }

                //如果还没有账号  去掉mac余量要求  走iphone
                if (accountDO == null) {
                    queryModel.setMacRemainingLimit(null);
                    queryModel.setIphoneRemainingLimit(0);
                    bundleIdPlatform = BundleIdPlatform.IOS;
                    accountDO = developerAccountService.getAvailableDeveloperAccount(queryModel);
                }
            }

        } else if (createModel.getAccountType().equals(AppleAccountType.INDEPENDENT_POOL)) {
            queryModel.setAccountBelongType(AppleAccountType.INDEPENDENT_POOL.getType());
            queryModel.setUserId(createModel.getAppAccountId());
            if (null != createModel.getAppAccountId()) {
                queryModel.setAccountId(createModel.getAppAccountId());
            }
            accountDO = developerAccountService.getAvailableDeveloperAccount(queryModel);
        }

        Assert.notNull(accountDO, "无可用库存");

        log.info("{}获取到的账号信息为:{}", createModel.getUdid(), JSON.toJSONString(accountDO));
        try {

            //获取token
            String token = TokenUtil.generateToken(accountDO.getIssId(), accountDO.getKId(), accountDO.getP8Url(), fileApi);
            //添加设备
            Device device = AppleConnectUtil.createDevice(createModel.getUdid(), "test", token, bundleIdPlatform);
            log.info("添加设备返回结果为:{}", JSON.toJSONString(device));
            model.setDeviceId(device.getId());
            model.setDeviceModel(device.getAttributes().getModel());
            if (StringUtils.equals(device.getAttributes().getStatus().name(), "PROCESSING") || StringUtils.equals(device.getAttributes().getStatus().name(), "INELIGIBLE")) {
                log.info("苹果返回状态为添加中，重试一下");
                Thread.sleep(1000);
                device = AppleConnectUtil.getDeviceByUdId(token, createModel.getUdid());
            }

            if (StringUtils.equals(device.getAttributes().getStatus().name(), "PROCESSING") || StringUtils.equals(device.getAttributes().getStatus().name(), "INELIGIBLE")) {
                developerAccountService.refreshRemaining(accountDO.getId(), null);
                log.info("设备添加中,请稍后再试");
                if (ClassType.SECOND.equals(createModel.getClassType())) {

                    log.info("秒出订单 重新获取设备");
                    // 如果账号不是优先的 则打开预约状态 并且禁用账号
                    if (accountDO.getPreferFlag() == 0) {
                        log.info("当前账号非秒出账号，打开预约状态{}", accountDO.getDeveloperName());
                        accountDO.setAppointmentFlag(1);
                        accountDO.setEnableFlag(0);
                        developerAccountService.updateByIdNow(accountDO);
                    }
                    if (null == queryModel.getNotInAccountIds()) {
                        queryModel.setNotInAccountIds(Lists.newArrayList(accountDO.getId()));
                    } else {
                        queryModel.getNotInAccountIds().add(accountDO.getId());
                    }
                    accountDO = developerAccountService.getAvailableDeveloperAccount(queryModel);
                    Assert.notNull(accountDO, "无可用库存");
                } else {
                    model.setP12Password(accountDO.getP12Password());
                    model.setP12Url(accountDO.getP12Url());
                    model.setCerId(accountDO.getCId());
                    model.setCerNumber(accountDO.getCerNumber());
                    model.setCerName(accountDO.getCerName());
                    model.setAppAccountId(accountDO.getId());
                    model.setAccountType(accountDO.getAccountBelongType());
                    return model;
                }
            }
//        deviceIds.add(device.getId());
            model.setP12Password(accountDO.getP12Password());
            model.setP12Url(accountDO.getP12Url());
            model.setCerId(accountDO.getCId());
            model.setCerNumber(accountDO.getCerNumber());
            model.setCerName(accountDO.getCerName());
            model.setAppAccountId(accountDO.getId());
            model.setAccountType(accountDO.getAccountBelongType());
            developerAccountService.refreshRemaining(accountDO.getId(), null);
            //创建描述文件
            Profile profile = AppleConnectUtil.createProfile(token, accountDO.getBId(), accountDO.getCId(), Lists.newArrayList(device.getId()));
            Assert.notNull(profile, "生成描述文件失败");
            log.info("创建描述文件返回结果为:{}", JSON.toJSONString(profile));


            File tempFile = FileUtil.createTempFile(".mobileprovision", false);
            FileUtil.writeBytes(Base64.getDecoder().decode(profile.getAttributes().getProfileContent()), tempFile);
            String fileName = UUID.fastUUID() + "." + FileUtil.getSuffix(tempFile);
            String mpFilePath = fileApi.createFile(fileName, "mb", FileUtil.readBytes(tempFile));
            log.info("生成描述文件成功,文件路径为:{}", mpFilePath);

            model.setProfile(profile);
            model.setCreateTime(profile.getAttributes().getCreatedDate());
            model.setExpireTime(profile.getAttributes().getExpirationDate());
            model.setProfileUrl(mpFilePath);
        } catch (ResponseProcessingException e) {

            String message = e.getMessage();

            Throwable cause = e.getCause();
            if (cause instanceof AppStoreConnectException) {
                AppStoreConnectException appStoreConnectException = (AppStoreConnectException) cause;
                message = "调用苹果接口失败,错误码:【" + appStoreConnectException.getErrorResponse().getErrors().get(0).getCode() + "】,错误信息:【" + appStoreConnectException.getErrorResponse().getErrors().get(0).getDetail() + "】";
            }
            log.error("获取证书失败", e);
            String msg = buildMdMsg(message, accountDO.getDeveloperName(), createModel.getUserName(), createModel.getDeviceType().name(), createModel.getUdid());
            wechatMsgApi.sendMsg(msg);
            throw e;
        }

        return model;
    }

    private String buildMdMsg(String errorMsg, String cerName, String userName, String platform, String udid) {
        return "## 添加设备出错\n" +
                "**时间**:  " + DateUtil.now() + "\n" +
                "\n" +
                "**错误**: " + errorMsg + "\n" +
                "\n" +
                "**证书名称**:  " + cerName + "\n" +
                "\n" +
                "**用户**: " + userName + "\n" +
                "\n" +
                "**平台**: " + platform + "\n" +
                "\n" +
                "**UDID**: " + udid;
    }


    @Override
    public AppleDeviceDO findByUdidAndUserId(String udid, Long userId) {
        return appleDeviceMapper.selectByUdidAndUserId(udid, userId);
    }

    @Override
    public AppleDeviceDO findByUdid(String udid) {
        return appleDeviceMapper.selectByUdid(udid);
    }

    @Override
    public List<AppleDeviceDO> getByUserId(Long userId) {
        return appleDeviceMapper.selectList(new LambdaQueryWrapperX<AppleDeviceDO>().eq(AppleDeviceDO::getUserId, userId));
    }

    @Override
    public String reGetMobileProvision(Long id) throws Exception {
        AppleDeviceDO deviceDO = appleDeviceMapper.selectById(id);
        Assert.notNull(deviceDO, "设备不存在");
        if (StringUtils.isNotBlank(deviceDO.getMpUrl())) {
            return deviceDO.getMpUrl();
        }

        DeveloperAccountDO accountDO = developerAccountService.getById(deviceDO.getAppAccountId());
        Assert.notNull(accountDO, "账号不存在");

        //获取token
        String token = TokenUtil.generateToken(accountDO.getIssId(), accountDO.getKId(), accountDO.getP8Url(), fileApi);

        Device device = AppleConnectUtil.getDeviceByUdId(token, deviceDO.getUdid());
        if (StringUtils.equals(device.getAttributes().getStatus().name(), DeviceAttributes.Status.PROCESSING.name())) {
            Assert.isTrue(false, "苹果官方审核中,预计72小时可用");
        } else if (StringUtils.equals(device.getAttributes().getStatus().name(), DeviceAttributes.Status.INELIGIBLE.name())) {
            Assert.isTrue(false, "苹果官方审核中,预计7-30天可用");
        }
        Assert.isTrue(StringUtils.equals(device.getAttributes().getStatus().name(), DeviceAttributes.Status.ENABLED.name()), "苹果官方审核中");

        Profile profile = AppleConnectUtil.createProfile(token, accountDO.getBId(), accountDO.getCId(), Lists.newArrayList(device.getId()));
        if (null == profile) {
            return null;
        }
        log.info("创建描述文件返回结果为:{}", JSON.toJSONString(profile));


        File tempFile = FileUtil.createTempFile(".mobileprovision", false);
        FileUtil.writeBytes(Base64.getDecoder().decode(profile.getAttributes().getProfileContent()), tempFile);
        String fileName = UUID.fastUUID() + "." + FileUtil.getSuffix(tempFile);
        String mpFilePath = fileApi.createFile(fileName, "mb", FileUtil.readBytes(tempFile));
        log.info("生成描述文件成功,文件路径为:{}", mpFilePath);


        deviceDO.setMpUrl(mpFilePath);
        deviceDO.setUpdateTime(DateUtil.toLocalDateTime(new Date()));

        appleDeviceMapper.updateById(deviceDO);

        developerAccountService.refreshRemaining(accountDO.getId(), null);

        return mpFilePath;
    }


    @Override
    public void reGetMobileProvisionTask() throws Exception {
        List<AppleDeviceDO> deviceDOList = appleDeviceMapper.selectList(new LambdaQueryWrapperX<AppleDeviceDO>()
                .eq(AppleDeviceDO::getClassType, String.valueOf(ClassType.APPOINTMENT.getType()))
                .and(wrapper -> wrapper.or()
                        .isNull(AppleDeviceDO::getMpUrl)
                        .or()
                        .eq(AppleDeviceDO::getMpUrl, "")
                ));
        if (CollUtil.isEmpty(deviceDOList)) {
            return;
        }
        for (AppleDeviceDO deviceDO : deviceDOList) {
            try {
                log.info("设备{}重新获取描述文件", deviceDO.getUdid());
                reGetMobileProvision(deviceDO.getId());
            } catch (Exception e) {
                log.error("设备{}重新获取描述文件异常", deviceDO.getUdid(), e);
            }
        }
    }


    @Override
    public void cerCheck() throws Exception {
        log.info("开始证书掉签检查");
        // todo ljq 校验某段时间之内的应该
        List<AppleDeviceDO> deviceDOS = appleDeviceMapper.selectList(new LambdaQueryWrapperX<AppleDeviceDO>()
                .eq(AppleDeviceDO::getDropFlag, 0)
                .isNotNull(AppleDeviceDO::getMpUrl)
                .ne(AppleDeviceDO::getMpUrl, ""));

        if (CollUtil.isEmpty(deviceDOS)) {
            return;
        }

        deviceDOS.forEach(appleDeviceDO -> {
            try {
                String p12Url = appleDeviceDO.getP12Url();
                String p12Password = appleDeviceDO.getP12Password();

                if (StringUtils.isBlank(p12Url) || StringUtils.isBlank(p12Password)) {
                    return;
                }

                String p12Path = CharSequenceUtil.subAfter(p12Url, "/get/", false);
                String p12Config = p12Url.substring(p12Url.indexOf("/file/") + "/file/".length(), p12Url.indexOf("/get/"));
                String p12FilePath = fileApi.getFilePath(Long.valueOf(p12Config), p12Path);

                String p12Str = Base64Encoder.encode(FileUtil.readBytes(p12FilePath));
                CertStatusDTO certStatusDTO = OCSPUtil.checkCertStatus(p12Str, p12Password, 1);
                CertUtil.getCertInfo(p12Str, p12Password, certStatusDTO);
                if(StringUtils.isNotBlank(certStatusDTO.getCertExpireTime())){
                    appleDeviceDO.setCerExpireTime(DateUtil.parseDateTime(certStatusDTO.getCertExpireTime()));
                }
                log.info("设备{}证书掉签检查结果为:{}", appleDeviceDO.getUdid(), JSON.toJSONString(certStatusDTO));
                if (certStatusDTO.getStatus() != 0 || (null != certStatusDTO.getCertRemainingDays() && certStatusDTO.getCertRemainingDays() < 0)) {
                    appleDeviceDO.setDropFlag(true);
                }
                appleDeviceDO.setCerStatus(String.valueOf(certStatusDTO.getStatus()));
                appleDeviceMapper.updateById(appleDeviceDO);
            } catch (Exception e) {
                log.error("证书掉签检查异常", e);
            }
        });
    }

    @Override
    public MobileProvisionExtractMode extractMobileProvision(String mobileProvisionUrl) throws Exception {
        String path = CharSequenceUtil.subAfter(mobileProvisionUrl, "/get/", false);
        String config = mobileProvisionUrl.substring(mobileProvisionUrl.indexOf("/file/") + "/file/".length(), mobileProvisionUrl.indexOf("/get/"));
        String filePath = fileApi.getFilePath(Long.valueOf(config), path);

        Map<String, Object> map = MbUtil.parseProvisionFile(filePath);
        MobileProvisionExtractMode extractMode = new MobileProvisionExtractMode();
        extractMode.setAppIdName(map.get("appIdName").toString());
        extractMode.setTeamIdentifier(map.get("teamIdentifier").toString());
        extractMode.setCreationDate(map.get("creationDate").toString());
        extractMode.setExpirationDate(map.get("expirationDate").toString());
        extractMode.setTeamName(map.get("teamName").toString());
        extractMode.setUdid(map.get("udid").toString());
        return extractMode;
    }


    /**
     * 根据设备Id和用户id查询设备
     *
     * @param id
     * @param userId
     * @return
     */
    @Override
    public AppleDeviceResp selectCertificate(String id, Long userId) {
        QueryWrapper<AppleDeviceDO> queryWrapperX = new QueryWrapper<AppleDeviceDO>()
                .eq("id", id)
                .eq("user_id", userId)
                .orderByDesc("id")
                .last("LIMIT 1");
        AppleDeviceDO appleDeviceDO = appleDeviceMapper.selectOne(queryWrapperX);
        if(appleDeviceDO==null || appleDeviceDO.getId()==null) {
            return null;
        }
        log.info(JSONUtil.toJsonStr(appleDeviceDO));
        AppleDeviceResp resp = new AppleDeviceResp();
        resp.setId(String.valueOf(appleDeviceDO.getId()));
        resp.setUdid(appleDeviceDO.getUdid());
        // 0公共池 1独立池
        if(ObjectUtil.isEmpty(appleDeviceDO.getClassType())){
            resp.setType(0);
        }else {
            resp.setType(Integer.valueOf(appleDeviceDO.getClassType()));
        }
        resp.setPool(appleDeviceDO.getPoolType());
        // 证书类别  0实时 1预约

        resp.setAddTime(appleDeviceDO.getCreateTime().atZone(ZoneId.systemDefault()).toEpochSecond());
        // base64描述文件
        resp.setMobileprovision(appleDeviceDO.getMpUrl());
        // base64 P12文件
        resp.setP12(appleDeviceDO.getP12Url());
        // 是否为售后证书
        resp.setWarranty(true);
        // 售后截止时间
        if (appleDeviceDO.getTimeout() != null) {
            resp.setWarrantyTime(appleDeviceDO.getCreateTime().plusDays(appleDeviceDO.getTimeout()));
        } else {
            resp.setWarrantyTime(appleDeviceDO.getCreateTime());
        }
        // 是否掉签
        resp.setState(!appleDeviceDO.getDropFlag());
        resp.setPName(appleDeviceDO.getCerName());
        if("VT2".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("0");
        }else if ("VT3".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("1");
        }else if ("VT5".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("2");
        }else if ("VT6".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("3");
        }else if ("VT1".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("4");
        }else if ("VT4".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("5");
        }else {
            resp.setShtype("0");
        }
        log.info(JSONUtil.toJsonStr(resp));
        return resp;
    }

    /**
     * 根据设备udid和用户id查询设备
     *
     * @param udid
     * @param id
     * @return
     */
    @Override
    public AppleDeviceResp getDeviceByUdidAndUserId(String udid, Long id) {

        AppleDeviceDO appleDeviceDO = appleDeviceMapper.selectOne(
                new QueryWrapper<AppleDeviceDO>()
                        .eq("udid", udid)
                        .eq("user_id", id)
                        .orderByDesc("id")   // 按 id 倒序
                        .last("LIMIT 1")     // 只取一条
        );
        if(appleDeviceDO==null) {
            return new AppleDeviceResp();
        }
        AppleDeviceResp resp = new AppleDeviceResp();
        resp.setId(String.valueOf(appleDeviceDO.getId()));
        resp.setUdid(appleDeviceDO.getUdid());
        // 0公共池 1独立池
        resp.setPool(appleDeviceDO.getPoolType());
        // 证书类别  0实时 1预约
        if(ObjectUtil.isNotEmpty(appleDeviceDO.getClassType())){
            resp.setType(Integer.valueOf(appleDeviceDO.getClassType()));
        }else {
            resp.setType(0);
        }
        resp.setAddTime(appleDeviceDO.getCreateTime().atZone(ZoneId.systemDefault()).toEpochSecond());
        // base64描述文件
        resp.setMobileprovision(appleDeviceDO.getMpUrl());
        // base64 P12文件
        resp.setP12(appleDeviceDO.getP12Url());
        // 是否为售后证书
        resp.setWarranty(true);
        // 售后截止时间
        if (appleDeviceDO.getTimeout() != null) {
            resp.setWarrantyTime(appleDeviceDO.getCreateTime().plusDays(appleDeviceDO.getTimeout()));
        } else {
            resp.setWarrantyTime(appleDeviceDO.getCreateTime());
        }
        // 是否掉签
        resp.setState(!appleDeviceDO.getDropFlag());
        resp.setPName(appleDeviceDO.getCerName());
        if("VT2".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("0");
        }else if ("VT3".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("1");
        }else if ("VT5".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("2");
        }else if ("VT6".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("3");
        }else if ("VT1".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("4");
        }else if ("VT4".equals(appleDeviceDO.getVersionTypeCode())){
            resp.setShtype("5");
        }else {
            resp.setShtype("0");

        }        return resp;
    }

}
